#!/usr/bin/python
# -*- coding: cp1250 -*-

from pepe.glib import *

zf9 = lambda x: string.zfill(str(x), 9)
# 2683099 -> 002-683-099
x3x = lambda x: "%s-%s-%s" % (zf9(x)[:3], zf9(x)[3:6], zf9(x)[6:9])

def main(filemask, minlen=1, prefix='', col_separator='\t'):
    print '''
    add incremental unique id'''
    errcnt = 0
    minlen = int(minlen)

    for f in sorted(glob.glob(filemask)):

        '''2010-10-01_1023 vp
        # handling file mask as ... f = aa-dataonly\*.dat
        fname = fw_slash(f)
        # fname = aa-dataonly/*.dat
        fname = string.split(fname, '/')[-1]
        # fname = *.dat
        fname = string.split(fname, '.')[0]
        # fname = *
        '''
        fname = string.split(f, '\x5C')[-1]
        fname = string.split(fname, '.')[0]

        print '    ', timenow(), fname
        #ofname = "%s_%s_" % (chid, f)
        #ofname = "%s_" % (f)

        # 2010-10-22_2257 vp
        ## using underscore instead dot because .# utilities 
        ## cut out everything after dot and then it is not clear 
        ## whether utility was run on original file or on output
        ## of other .# utility that processed given file
        #of = open(fname + '.data_add_unique_id.#', 'wb')
        #ef = open('err_' + fname + '.data_add_unique_id.#', 'wb')
        #2011-06-15_1425 vip
        #of = open(fname + 'uipx_%s' % (fname,), 'wb')
        #2011-09-12_0914
        of = open('uipx_%s' % (fname,), 'wb')
        #of = open(fname + '_iuid.#', 'wb')
        # uidi - incremental unique identifier

        lino = 0
       
        # take first 3 characters from fname if not explicit prefix
        if prefix == '':
            fname_012 = fname[:3]
        else:
            fname_012 = prefix
        
        for line in bt.lines(f):
            lino += 1

            uid = "%s-%s" % (fname_012, x3x(lino))
            
            of.write("%s%s%s" % (uid, col_separator, line))

        of.close()
        #chid = iter.next()
        # report errors count
        print '    ', timenow(), '\n'

if __name__ == "__main__":
    """"""
    if  len(sys.argv) == 2:
        main(filemask=sys.argv[1], minlen=1)
    elif len(sys.argv) == 3:
        main(filemask=sys.argv[1], minlen=sys.argv[2])
    else:
        print """

        data_add_unique_id.py <file(s)-mask> [<min-len>] [<custom-prefix>]

        file(s)-name (mandatory)
            data filename(s) (mask) to be processed

        min-length (optional)
            defines minimal number of non empty (non space or tab) characters 
            default 1 (row is reported as error if less than 1 non-empty /not space or tab/ chars)
            
        custom-prefix (optional)
            custom prefix for unique id
            default are first 3 characters from file name
        """
